<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Upload File</title>
    <script src="https://cdn.jsdelivr.net/npm/spark-md5"></script>
</head>
<body>
    <h1>Upload File</h1>
    <form id="uploadForm" method="post" enctype="multipart/form-data">
        <input type="file" id="fileInput" name="file">
        <input type="button" value="Upload" onclick="handleUpload()">
    </form>
    <div id="status"></div>
    <script>
        async function handleUpload() {
            const file = document.getElementById('fileInput').files[0];
            if (!file) {
                alert('Please select a file');
                return;
            }

            // Calculate MD5
            const md5 = await calculateMD5(file);
            // Check if file exists on server
            const response = await fetch('/check_file', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ md5: md5, fileName: file.name ,fileSize:file.size})
            });

            if (response.ok) {
                const result = await response.json();
                if (result.exists) {
                    document.getElementById('status').innerText = 'File already exists. Instant upload success!';
                } else {
                    // Perform actual upload
                    const formData = new FormData();
                    formData.append('file', file);

                    const uploadResponse = await fetch('/upload', {
                        method: 'POST',
                        body: formData
                    });

                    if (uploadResponse.ok) {
                        document.getElementById('status').innerText = 'File uploaded successfully!';
                        alert('File uploaded successfully!');
                    } else {
                        document.getElementById('status').innerText = 'File upload failed!';
                        alert('File upload failed!');
                    }
                }
            } else {
                alert('Error checking file existence: '+ response.status +response.statusText);
                document.getElementById('status').innerText = 'Error checking file existence.';
            }
        }

        async function calculateMD5(file) {
            return new Promise((resolve, reject) => {
                var spark = new SparkMD5.ArrayBuffer();
                var reader = new FileReader();

                reader.onload = function (e) {
                    spark.append(e.target.result);
                    const md5 = spark.end();
                    resolve(md5);
                };

                reader.onerror = function (e) {
                    reject('File reading failed');
                };

                reader.readAsArrayBuffer(file);
            });
        }
    </script>
</body>
</html>